package com.photo.photePro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.photo.photePro.entity.Like;
import com.photo.photePro.entity.Photo;
import com.photo.photePro.mapper.LikeMapper;
import com.photo.photePro.service.LikeService;
import com.photo.photePro.service.PhotoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 点赞服务实现类
 */
@Slf4j
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {

    @Autowired
    private PhotoService photoService;

    @Override
    public Page<Like> pageUserLikes(int page, int pageSize, Long userId) {
        Page<Like> pageInfo = new Page<>(page, pageSize);
        
        // 1. 先查询用户点赞记录
        LambdaQueryWrapper<Like> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Like::getUserId, userId);
        queryWrapper.orderByDesc(Like::getCreateTime);
        
        page(pageInfo, queryWrapper);
        
        // 2. 补充每个点赞记录的作品信息
        List<Like> records = pageInfo.getRecords();
        if (records != null && !records.isEmpty()) {
            List<Long> photoIds = records.stream()
                    .map(Like::getPhotoId)
                    .collect(Collectors.toList());
            
            // 批量查询作品信息
            List<Photo> photos = photoService.listByIds(photoIds);
            
            // 组装数据
            for (Like like : records) {
                for (Photo photo : photos) {
                    if (like.getPhotoId().equals(photo.getId())) {
                        like.setTitle(photo.getTitle());
                        like.setDescription(photo.getDescription());
                        like.setImgUrl(photo.getImgUrl());
                        like.setAuthor(photo.getAuthor());
                        like.setViewCount(photo.getViewCount());
                        break;
                    }
                }
            }
        }
        
        return pageInfo;
    }

    @Override
    public boolean isLiked(Long photoId, Long userId) {
        LambdaQueryWrapper<Like> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Like::getPhotoId, photoId);
        queryWrapper.eq(Like::getUserId, userId);
        
        return count(queryWrapper) > 0;
    }

    @Override
    public boolean addLike(Long photoId, Long userId) {
        // 先检查是否已点赞
        if (isLiked(photoId, userId)) {
            return true;
        }
        
        // 添加点赞
        Like like = new Like();
        like.setPhotoId(photoId);
        like.setUserId(userId);
        like.setCreateTime(LocalDateTime.now());
        like.setUpdateTime(LocalDateTime.now());
        
        boolean saveResult = save(like);
        
        if (saveResult) {
            // 更新作品的点赞数（这里假设Photo实体有likeCount字段）
            // 如果没有这个字段，可以移除这段代码
            /*
            Photo photo = photoService.getById(photoId);
            if (photo != null) {
                photo.setLikeCount(photo.getLikeCount() + 1);
                photoService.updateById(photo);
            }
            */
        }
        
        return saveResult;
    }

    @Override
    public boolean removeLike(Long photoId, Long userId) {
        LambdaQueryWrapper<Like> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Like::getPhotoId, photoId);
        queryWrapper.eq(Like::getUserId, userId);
        
        boolean removeResult = remove(queryWrapper);
        
        if (removeResult) {
            // 更新作品的点赞数（这里假设Photo实体有likeCount字段）
            // 如果没有这个字段，可以移除这段代码
            /*
            Photo photo = photoService.getById(photoId);
            if (photo != null && photo.getLikeCount() > 0) {
                photo.setLikeCount(photo.getLikeCount() - 1);
                photoService.updateById(photo);
            }
            */
        }
        
        return removeResult;
    }
} 